'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { Card, Table, Button, Modal, Form, Upload, DatePicker, Input, message, Tag, Space, Typography } from 'antd';
import { UploadOutlined, EyeOutlined } from '@ant-design/icons';
import Layout from '@/components/Layout';
import { getOfferApprovalList, approveOffer, OfferApprovalStatus } from '@/lib/onboarding';
import type { OfferApprovalInfo } from '@/lib/onboarding';
import dayjs from 'dayjs';
import debounce from 'lodash/debounce';

const OfferManagementPage = () => {
  // 状态定义
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [data, setData] = useState<OfferApprovalInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<OfferApprovalInfo | null>(null);
  const [form] = Form.useForm();
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState<string>('');
  const [selectedStatus, setSelectedStatus] = useState<OfferApprovalStatus>(OfferApprovalStatus.Approved);

  // 加载数据
  const loadData = async (page = currentPage, size = pageSize) => {
    try {
      setLoading(true);
      const response = await getOfferApprovalList({
        page,
        pageSize: size,
        status: undefined // 获取所有状态的记录
      });

      console.log('获取到的Offer数据:', {
        原始响应: response,
        状态码: response.code,
        总数: response.data?.total,
        数据列表: response.data?.row
      });

      if (response.code === 1) {
        setData(response.data.row);
        setTotal(response.data.total);
      } else {
        message.error(response.msg || '获取数据失败');
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    loadData();
  }, []);

  // 监听表单值变化
  useEffect(() => {
    const subscription = form.getFieldInstance('status')?.subscribe(() => {
      setSelectedStatus(form.getFieldValue('status'));
    });
    return () => subscription?.unsubscribe();
  }, [form]);

  // 处理审批 - 使用防抖
  const debouncedApprove = useCallback(
    debounce(async (values: any) => {
      if (!currentRecord?.id) {
        message.error('申请ID不能为空');
        return;
      }

      if (values.status === undefined) {
        message.error('审批状态不能为空');
        return;
      }

      try {
        setSubmitting(true);
        
        // 创建 FormData 对象
        const formData = new FormData();
        
        // 添加必需参数
        formData.append('id', String(currentRecord.id));
        formData.append('status', String(values.status));
        
        // 如果是通过，添加其他必需参数
        if (values.status === OfferApprovalStatus.Approved) {
          if (!values.content || !values.offerFile?.[0]?.originFileObj || !values.onboardingTime || !values.onboardingPlace || !values.expiryTime) {
            message.error('请填写完整所有必需信息');
            setSubmitting(false);
            return;
          }
          
          formData.append('content', values.content);
          formData.append('offerFile', values.offerFile[0].originFileObj);
          formData.append('onboardingTime', values.onboardingTime.format('YYYY-MM-DDTHH:mm:ss'));
          formData.append('onboardingPlace', values.onboardingPlace);
          formData.append('expiryTime', values.expiryTime.format('YYYY-MM-DDTHH:mm:ss'));
        }

        // 打印 FormData 内容以便调试
        console.log('FormData 内容:', {
          id: formData.get('id'),
          status: formData.get('status'),
          content: formData.get('content'),
          offerFile: formData.get('offerFile'),
          onboardingTime: formData.get('onboardingTime'),
          onboardingPlace: formData.get('onboardingPlace'),
          expiryTime: formData.get('expiryTime')
        });

        const response = await approveOffer({
          id: currentRecord.id,
          status: values.status,
          content: values.content,
          offerFile: values.offerFile?.[0]?.originFileObj,
          onboardingTime: values.onboardingTime?.format('YYYY-MM-DDTHH:mm:ss'),
          onboardingPlace: values.onboardingPlace,
          expiryTime: values.expiryTime?.format('YYYY-MM-DDTHH:mm:ss')
        });

        if (response.code === 1) {
          message.success('审批成功');
          setApprovalModalVisible(false);
          form.resetFields();
          loadData();
        } else {
          message.error(response.data || response.msg || '审批失败');
        }
      } catch (error: any) {
        console.error('审批失败:', error);
        const errorMsg = error.response?.data?.data || error.response?.data?.msg || error.message || '审批失败';
        message.error(errorMsg);
      } finally {
        setSubmitting(false);
      }
    }, 500),
    [currentRecord, form, loadData]
  );

  // 处理审批表单提交
  const handleApprove = (values: any) => {
    if (submitting) return;
    debouncedApprove(values);
  };

  // 表格列定义
  const columns = [
    {
      title: '应聘者',
      dataIndex: 'intervieweeName',
      key: 'intervieweeName',
      width: 120,
      render: (name: string | null) => name || '匿名',
    },
    {
      title: '说明',
      dataIndex: 'instructions',
      key: 'instructions',
      width: 100,
      align: 'center' as const,
      render: (text: string) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            setCurrentDetail(text);
            setDetailModalVisible(true);
          }}
        >
          查看
        </Button>
      ),
    },
    {
      title: '申请人',
      dataIndex: 'applicantName',
      key: 'applicantName',
      width: 120,
    },
    {
      title: '审批人',
      dataIndex: 'approverName',
      key: 'approverName',
      width: 120,
      render: (approverId: string | null, record: OfferApprovalInfo) => {
        if (record.status === OfferApprovalStatus.Pending) {
          return '未审批';
        }
        return approverId || '-';
      },
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: OfferApprovalStatus) => {
        const statusMap = {
          [OfferApprovalStatus.Pending]: { text: '待审批', color: 'blue' },
          [OfferApprovalStatus.Approved]: { text: '已通过', color: 'green' },
          [OfferApprovalStatus.Rejected]: { text: '已拒绝', color: 'red' },
        };
        const config = statusMap[status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time: string | null) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '未申请',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '发送时间',
      dataIndex: 'sendTime',
      key: 'sendTime',
      width: 180,
      render: (time: string | null, record: OfferApprovalInfo) => {
        if (record.status === OfferApprovalStatus.Pending) {
          return '未审批';
        }
        return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
    },
    {
      title: '有效期至',
      dataIndex: 'expiryTime',
      key: 'expiryTime',
      width: 180,
      render: (time: string | null, record: OfferApprovalInfo) => {
        if (record.status === OfferApprovalStatus.Pending) {
          return '未审批';
        }
        return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
    },
    {
      title: '接受结果',
      dataIndex: 'result',
      key: 'result',
      width: 100,
      render: (result: number) => {
        const resultMap: Record<number, { text: string; color: string }> = {
          0: { text: '未选择', color: 'default' },
          1: { text: '已接受', color: 'green' },
          2: { text: '已拒绝', color: 'red' },
        };
        const config = resultMap[result] || resultMap[0];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 100,
      render: (_: any, record: OfferApprovalInfo) => (
        <Space>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              setCurrentRecord(record);
              setApprovalModalVisible(true);
            }}
            disabled={record.status !== OfferApprovalStatus.Pending}
          >
            审批
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Layout>
      <div className="p-4">
        <Card title="Offer管理">
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            scroll={{ x: 1500 }}
            pagination={{
              current: currentPage,
              pageSize,
              total,
              onChange: (page, size) => {
                setCurrentPage(page);
                setPageSize(size || 10);
                loadData(page, size);
              },
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
          />
        </Card>

        <Modal
          title="审批 Offer"
          open={approvalModalVisible}
          onCancel={() => {
            if (!submitting) {
              setApprovalModalVisible(false);
              form.resetFields();
              setSelectedStatus(OfferApprovalStatus.Approved);
            }
          }}
          onOk={() => !submitting && form.submit()}
          okButtonProps={{ loading: submitting }}
          cancelButtonProps={{ disabled: submitting }}
          maskClosable={!submitting}
          closable={!submitting}
          width={600}
          confirmLoading={submitting}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleApprove}
            initialValues={{
              status: OfferApprovalStatus.Approved
            }}
            disabled={submitting}
          >
            <div style={{ 
              filter: submitting ? 'blur(1px)' : 'none',
              pointerEvents: submitting ? 'none' : 'auto',
              opacity: submitting ? 0.7 : 1,
              transition: 'all 0.3s'
            }}>
              <Form.Item
                label="审批结果"
                name="status"
                rules={[{ required: true, message: '请选择审批结果' }]}
              >
                <Space>
                  <Button
                    type={selectedStatus === OfferApprovalStatus.Approved ? 'primary' : 'default'}
                    onClick={() => {
                      form.setFieldsValue({ status: OfferApprovalStatus.Approved });
                      setSelectedStatus(OfferApprovalStatus.Approved);
                    }}
                    style={{
                      width: '120px',
                      height: '40px',
                      ...(selectedStatus === OfferApprovalStatus.Approved ? {
                        backgroundColor: '#52c41a',
                        borderColor: '#52c41a',
                        color: '#fff',
                        fontWeight: 'bold',
                        boxShadow: '0 2px 4px rgba(82, 196, 26, 0.4)'
                      } : {})
                    }}
                  >
                    通过
                  </Button>
                  <Button
                    type={selectedStatus === OfferApprovalStatus.Rejected ? 'primary' : 'default'}
                    danger
                    onClick={() => {
                      form.setFieldsValue({ status: OfferApprovalStatus.Rejected });
                      setSelectedStatus(OfferApprovalStatus.Rejected);
                    }}
                    style={{
                      width: '120px',
                      height: '40px',
                      ...(selectedStatus === OfferApprovalStatus.Rejected ? {
                        backgroundColor: '#ff4d4f',
                        borderColor: '#ff4d4f',
                        color: '#fff',
                        fontWeight: 'bold',
                        boxShadow: '0 2px 4px rgba(255, 77, 79, 0.4)'
                      } : {})
                    }}
                  >
                    拒绝
                  </Button>
                </Space>
              </Form.Item>

              {selectedStatus === OfferApprovalStatus.Approved && (
                <>
                  <Form.Item
                    label="邮件内容"
                    name="content"
                    rules={[{ required: true, message: '请输入邮件内容' }]}
                  >
                    <Input.TextArea rows={4} placeholder="请输入发送给应聘者的邮件内容" />
                  </Form.Item>

                  <Form.Item
                    label="Offer 附件"
                    name="offerFile"
                    valuePropName="fileList"
                    getValueFromEvent={(e) => {
                      if (Array.isArray(e)) return e;
                      return e?.fileList;
                    }}
                    rules={[{ required: true, message: '请上传 Offer 附件' }]}
                  >
                    <Upload 
                      maxCount={1} 
                      beforeUpload={(file) => {
                        const isPDF = file.type === 'application/pdf';
                        if (!isPDF) {
                          message.error('只能上传 PDF 格式的文件！');
                        }
                        return false;
                      }}
                      accept=".pdf"
                    >
                      <Button icon={<UploadOutlined />}>选择 PDF 文件</Button>
                    </Upload>
                  </Form.Item>

                  <Form.Item
                    label="入职办理时间"
                    name="onboardingTime"
                    rules={[{ required: true, message: '请选择入职办理时间' }]}
                  >
                    <DatePicker
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      style={{ width: '100%' }}
                    />
                  </Form.Item>

                  <Form.Item
                    label="入职办理地点"
                    name="onboardingPlace"
                    rules={[{ required: true, message: '请输入入职办理地点' }]}
                  >
                    <Input placeholder="请输入入职办理地点" />
                  </Form.Item>

                  <Form.Item
                    label="Offer 有效期"
                    name="expiryTime"
                    rules={[{ required: true, message: '请选择 Offer 有效期' }]}
                  >
                    <DatePicker
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      style={{ width: '100%' }}
                    />
                  </Form.Item>
                </>
              )}
            </div>
          </Form>
        </Modal>

        <Modal
          title="说明详情"
          open={detailModalVisible}
          onCancel={() => setDetailModalVisible(false)}
          footer={null}
        >
          <Typography.Paragraph style={{ whiteSpace: 'pre-wrap' }}>
            {currentDetail}
          </Typography.Paragraph>
        </Modal>
      </div>
    </Layout>
  );
};

export default OfferManagementPage; 